package com.have.blog.admin.service.impl;

import com.github.pagehelper.PageHelper;
import com.have.blog.admin.constant.AdminMessageConstant;
import com.have.blog.admin.domain.dto.BlogLinkDto;
import com.have.blog.admin.service.BlogLinkService;
import com.have.blog.admin.utils.SecurityUtil;
import com.have.blog.base.enums.BlogStatus;
import com.have.blog.base.wrapper.Wrapper;
import com.have.blog.model.mapper.OuterLinkMapper;
import com.have.blog.model.models.OuterLink;
import com.have.blog.model.models.OuterLinkExample;
import com.have.blog.picture.service.PictureFeignApi;
import com.have.blog.utils.MyBeanUtils;
import com.have.blog.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

@Service
@SuppressWarnings("all")
public class BlogLinkServiceImpl implements BlogLinkService {

    @Autowired
    private OuterLinkMapper linkMapper;
    @Autowired
    private PictureFeignApi pictureFeignApi;

    @Override
    public List<BlogLinkDto> getList(BlogLinkDto blogLinkDto) {
        PageHelper.startPage(blogLinkDto.getPageNum(), blogLinkDto.getPageSize());
        OuterLinkExample example = new OuterLinkExample();
        OuterLinkExample.Criteria criteria = example.createCriteria();
        criteria.andStatusEqualTo(BlogStatus.ENABLE.getStatus());
        if (!StringUtils.isEmpty(blogLinkDto.getKeyword()) && !StringUtils.isEmpty(blogLinkDto.getKeyword().trim())) {
            criteria.andTitleLike("%" + blogLinkDto.getKeyword().trim() + "%");
        }
        if (blogLinkDto.getLinkStatus() != null) {
            criteria.andLinkStatusEqualTo(blogLinkDto.getLinkStatus());
        }
        if(!StringUtils.isEmpty(blogLinkDto.getOrderByAscColumn())) {
            String column = StringUtils.underLine(new StringBuffer(blogLinkDto.getOrderByAscColumn())).toString();
            example.setOrderByClause(column + " asc");
        }else if(!StringUtils.isEmpty(blogLinkDto.getOrderByDescColumn())) {
            String column = StringUtils.underLine(new StringBuffer(blogLinkDto.getOrderByDescColumn())).toString();
            example.setOrderByClause(column + " desc");
        } else {
            example.setOrderByClause("sort desc");
        }
        List<OuterLink> linkList = linkMapper.selectByExample(example);
        List<BlogLinkDto> resultList = MyBeanUtils.copyListProperties(linkList, BlogLinkDto::new);
        List<Integer> picUids = new ArrayList<>();
        resultList.forEach(item -> {
            if (item.getCoverPictureUid() != null) {
                picUids.add(item.getCoverPictureUid());
            }
        });
        if (!CollectionUtils.isEmpty(picUids)) {
            Wrapper<Map<Integer, String>> picWrapper = pictureFeignApi.getPicturesUrl(picUids);
            if (picWrapper.isSuccess()) {
                Map<Integer, String> picMap = picWrapper.getData();
                for (BlogLinkDto linkDto : resultList) {
                    linkDto.setPhotoUrl(picMap.get(linkDto.getCoverPictureUid()));
                }
            }
        }
        return resultList;
    }

    @Override
    public Wrapper addBlogLink(BlogLinkDto BlogLinkDto) {
        OuterLink link = new OuterLink();
        MyBeanUtils.copyProperties(BlogLinkDto, link);
        Integer adminUid = SecurityUtil.getUserId();
        link.setStatus(BlogStatus.ENABLE.getStatus());
        link.setAdminUid(adminUid);
        int result = linkMapper.insert(link);
        if (result > 0) {
            // 通过消息队列发送邮件到站长邮箱
//        if(StringUtils.isNotEmpty(link.getEmail()) && CheckUtils.checkEmail(link.getEmail())) {
//            log.info("发送友链申请通过的邮件通知");
//            String linkApplyText =  "<a href=\" " + link.getUrl() + "\">" + link.getTitle() + "</a> 站长，您申请的友链已经成功上架~";
//            rabbitMqUtil.sendSimpleEmail(link.getEmail(), linkApplyText);
//        }

            // 删除redis中的友情链接
            deleteRedisBlogLinkList();
            return Wrapper.successWithMessage(AdminMessageConstant.INSERT_SUCCESS);
        }
        return Wrapper.failed(AdminMessageConstant.INSERT_FAIL);

    }


    @Override
    public Wrapper editBlogLink(BlogLinkDto BlogLinkDto) {
        OuterLink link = linkMapper.selectByPrimaryKey(BlogLinkDto.getUid());
        Integer linkStatus = link.getLinkStatus();
        link.setTitle(BlogLinkDto.getTitle());
        link.setSummary(BlogLinkDto.getSummary());
        link.setLinkStatus(BlogLinkDto.getLinkStatus());
        link.setUrl(BlogLinkDto.getUrl());
        link.setSort(BlogLinkDto.getSort());
        link.setEmail(BlogLinkDto.getEmail());
        link.setCoverPictureUid(BlogLinkDto.getCoverPictureUid());
        link.setUpdateTime(new Date());
        int result = linkMapper.updateByPrimaryKeySelective(link);
        if (result > 0) {
            // 友链从申请状态到发布状态，需要发送邮件到站长邮箱
//        if(StringUtils.isNotEmpty(link.getEmail()) && CheckUtils.checkEmail(link.getEmail())) {
//            if(ELinkStatus.APPLY.equals(linkStatus) && ELinkStatus.PUBLISH.equals(linkVO.geOuterLinkStatus())) {
//                log.info("发送友链申请通过的邮件通知");
//                String linkApplyText =  "<a href=\" " + link.getUrl() + "\">" + link.getTitle() + "</a> 站长，您申请的友链已经成功上架~";
//                rabbitMqUtil.sendSimpleEmail(link.getEmail(), linkApplyText);
//            }
//        }
            // 删除Redis中的BLOG_LINK
            deleteRedisBlogLinkList();
            return Wrapper.successWithMessage(AdminMessageConstant.UPDATE_SUCCESS);
        }
        return Wrapper.failed(AdminMessageConstant.UPDATE_FAIL);

    }


    @Override
    public Wrapper deleteBlogLink(BlogLinkDto BlogLinkDto) {
        OuterLink link = linkMapper.selectByPrimaryKey(BlogLinkDto.getUid());
        link.setStatus(BlogStatus.DISABLE.getStatus());
        int result = linkMapper.updateByPrimaryKeySelective(link);
        if (result > 0) {
            // 删除Redis中的BLOG_LINK
            deleteRedisBlogLinkList();
            return Wrapper.successWithMessage(AdminMessageConstant.DELETE_SUCCESS);
        }
        return Wrapper.failed(AdminMessageConstant.DELETE_FAIL);
    }

    @Override
    public Wrapper stickBlogLink(BlogLinkDto BlogLinkDto) {
        PageHelper.startPage(1, 1);
        OuterLink link = linkMapper.selectByPrimaryKey(BlogLinkDto.getUid());
        //查找出最大的那一个
        OuterLinkExample example = new OuterLinkExample();
        example.createCriteria()
                .andStatusEqualTo(BlogStatus.ENABLE.getStatus());
        example.setOrderByClause("sort desc");
        List<OuterLink> links = linkMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(links)) {
            return Wrapper.successWithMessage(AdminMessageConstant.OPERATION_SUCCESS);
        }
        OuterLink maxSort = links.get(0);
        if (maxSort.getUid().equals(link.getUid())) {
            return Wrapper.successWithMessage(AdminMessageConstant.OPERATION_SUCCESS);
        }
        Integer sortCount = maxSort.getSort() + 1;
        link.setSort(sortCount);
        int result = linkMapper.updateByPrimaryKeySelective(link);
        // 删除Redis中的BLOG_LINK
        if (result > 0) {
            deleteRedisBlogLinkList();
            return Wrapper.successWithMessage(AdminMessageConstant.OPERATION_SUCCESS);
        }
        return Wrapper.failed(AdminMessageConstant.OPERATION_FAIL);
    }

    private void deleteRedisBlogLinkList() {

    }
}
